package com.qf.controller.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.annotations.IgnoreLog;
import com.qf.annotations.LogOperationAnno;
import com.qf.entity.MyAuthUser;
import com.qf.entity.TLogbean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
杨威
2021/11/3
19:37
*/
@Aspect
@Component
public class LogAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    //定义切入点表达式 方法的全限定名称 类似于正则的写法
    //修饰符 返回值 包.类 方法名（参数） 异常
    @Pointcut("execution(* com.qf.controller.*Controller.*(..))")
    public void pointCut(){}

    //增强
    @Around("pointCut()")
    public Object processLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature signature =(MethodSignature) proceedingJoinPoint.getSignature();
        Object target = proceedingJoinPoint.getTarget();//获取controller类对象
        Method method = signature.getMethod();//正在执行的方法
        Object[] args = proceedingJoinPoint.getArgs();//获取传递的参数
        Object proceed = proceedingJoinPoint.proceed();//放行获取原始结果
        String[] parameterNames = signature.getParameterNames();//获取参数名称
        IgnoreLog annotation = method.getAnnotation(IgnoreLog.class);
        if(annotation!=null){
            //带有这个注解的 不记录日志
            return proceed;//直接返回原始结果 后面的日志就不运行了
        }
        TLogbean tLogbean=new TLogbean();
        //获取当前方法上 用于描述的注解
        LogOperationAnno logOperationAnno = method.getAnnotation(LogOperationAnno.class);
        if(logOperationAnno!=null){
            String value = logOperationAnno.value();//获取到介绍
            tLogbean.setOper(value);
        }
        //设置访问时间
        tLogbean.setAccessDate(new Date());
        if(parameterNames!=null){//将参数和值组合起来放到map汇总
            Map map=new HashMap();//保存所有参数的map集合
            for (int i = 0; i < parameterNames.length; i++) {
                String parameterName=parameterNames[i];
                Object arg=args[i];
                map.put(parameterName,arg);//将参数一个一个的放到map中
            }
            tLogbean.setParams(objectMapper.writeValueAsString(map));
        }
        //记录访问你的用户
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal != null) {
            Long i=((MyAuthUser)principal).getId();
            tLogbean.setUserId(i);
        }
        tLogbean.setResult(objectMapper.writeValueAsString(proceed));//将返回结果保存
        return proceed;//返回原始结果
    }
}
